import json

import markdown
from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.core import serializers

from django.shortcuts import render, get_object_or_404
from django.urls import reverse

from django.views.generic import ListView
from recommendation.models import Resume, New_Likes, Lab, Prize, Work
from .forms import ResumeForm
from django.http import HttpResponseRedirect, JsonResponse, QueryDict
from django.views.decorators.http import require_POST


class IndexView(ListView):
    model = Resume
    template_name = 'recommendation/index.html'
    context_object_name = 'resume_list'
    paginate_by = 4


@login_required
@require_POST
def resume_like(request):
    obj_id = request.POST['id']
    obj_type = request.POST['type']
    user = request.user
    ret = {'status': 0, 'number': 0}

    c = ContentType.objects.get(model=obj_type)
    paramrs = dict(content_type=c, object_id=obj_id, author=user)

    new_like = New_Likes.objects.filter(**paramrs)
    if(new_like):
        new_like.delete()
        ret['status'] = -1
    else:
        new_like = New_Likes(**paramrs).save()
        ret['status'] = 1

    number = New_Likes.objects.filter(content_type=c, object_id=obj_id).count()

    totallike = Resume.objects.get(id=obj_id)
    totallike.total_like = number
    totallike.save()

    ret['number'] = number
    return JsonResponse(ret)


@login_required
@require_POST
def add_lab(request):
    resum_id = request.POST.get('resume_id')
    content = request.POST.get('lab')
    ret = {}
    new_lab = Lab()
    new_lab.resume_id = resum_id
    new_lab.content = content
    new_lab.save()

    ret['status'] = 'ok'
    return JsonResponse(ret)


def is_like(request):
    obj_id = request.POST['id']
    obj_type = request.POST['type']
    user = request.user
    ret = {'status': 0}

    c = ContentType.objects.get(model=obj_type)
    paramrs = dict(content_type=c, object_id=obj_id, author=user)

    try:
        islike = New_Likes.objects.get(**paramrs)
        ret['status'] = 1
    except:
        ret['status'] = -1

    return JsonResponse(ret)


class SkillView(IndexView):
    def get_queryset(self):
        pk = self.kwargs['pk']
        paginate_by = 4

        return super(SkillView, self).get_queryset().filter(skill__name__in=[pk])


class CategoryView(IndexView):
    def get_queryset(self):
        pk = self.kwargs['pk']
        paginate_by = 4

        return super(CategoryView, self).get_queryset().filter(category__content__in=[pk])


def resume(request, pk):
    resume = get_object_or_404(Resume, pk=pk)
    resume.view_count += 1
    resume.save()
    resume.body = markdown.markdown(resume.body,
                                  extensions=[
                                     'markdown.extensions.extra',
                                     'markdown.extensions.codehilite',
                                     'markdown.extensions.toc',
                                  ])
    return render(request, 'recommendation/detail.html', context={'resume': resume, })



def pubResume2(request):
    if request.method != "POST":
        form = ResumeForm()
    else:
        workJson = request.POST.get('work')
        prizeJson = request.POST.get('prize')
        formJson = request.POST.get('myform')
        a = formJson.strip('"')  # 字符串多分号 导致字段不匹配
        formData = QueryDict(a)
        workData = json.loads(workJson)
        prizeData = json.loads(prizeJson)
        obj_id = ''
        form = ResumeForm(formData)

        if form.is_valid():
            resume = form.save(commit=False)
            resume.author = request.user
            resume.save()
            form.save_m2m()
            obj_id = resume.id
            saveData(resume.id, workData, prizeData)
        error = form.errors
        return JsonResponse({"work": error})
    return render(request, 'recommendation/PubResume2.html', context=locals())


def saveData(resume_id, workData, prizeData):
    try:
        Work.objects.filter(resume_id=resume_id).delete()
        Prize.objects.filter(resume_id=resume_id).delete()
    finally:
        for val in workData:
            new_work = Work()
            new_work.resume_id = resume_id
            new_work.name = val['name']
            new_work.position = val['position']
            new_work.content = val['introduce']
            new_work.save()

        for val in prizeData:
            new_prize = Prize()
            new_prize.resume_id = resume_id
            new_prize.content = val['prizename']
            new_prize.save()


def editResume(request,pk):
    obj_id = pk
    obj = get_object_or_404(Resume,id=pk)

    if request.user!=obj.author:
        return render(request, 'test.html')
    form = ResumeForm(instance=obj)

    work = Work.objects.filter(resume_id=pk)
    work_list = json.dumps(get_work_list(work),ensure_ascii=False)

    prize = Prize.objects.filter(resume_id=pk)
    prize_list = json.dumps(get_prize_list(prize),ensure_ascii=False)


    return render(request, 'recommendation/editResume.html', context=locals())


def get_work_list(work):
    work_list = []

    for val in work:
        dict = {}
        dict.update(name=val.name)
        dict.update(introduce=val.content)
        dict.update(position=val.position)
        work_list.append(dict)
    return work_list


def get_prize_list(prize):
    prize_list = []
    for val in prize:
        dict = {}
        dict.update(prizename=val.content)
        prize_list.append(dict)
    return prize_list